package com.ews.onlineexchange.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.security.RolesAllowed;
import javax.enterprise.inject.Model;
import javax.inject.Inject;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.Join;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import com.ews.onlineexchange.model.ServiceBuyer;
import org.apache.commons.lang3.StringUtils;

import com.ews.onlineexchange.model.Bulletin;
import com.ews.onlineexchange.model.ChooseType;
import com.ews.onlineexchange.model.TradeStatus;

@Model
@RolesAllowed( value = "businessManager" )
public class BusinessManagerAuditSuccessBulletinList extends EntityQuery<Bulletin> {

	/**
	 * 
	 */
	private static final long	serialVersionUID	= 1L;
	@Inject
	UserService					userService;

	public BusinessManagerAuditSuccessBulletinList() {
		setMaxResults( MAX_RESULTS_NORMAL );
		setOrder( "createDate desc" );
	}

	@Override
	protected List<Predicate> getRestrictions( CriteriaBuilder cb, Root<Bulletin> entity ) {

		List<Predicate> restrictions = new ArrayList<Predicate>();
		Join<Bulletin, ServiceBuyer> buyer = entity.join("buyer");
		//根据县区过滤
		super.addBulletinRegionRestriction(restrictions,buyer,cb);
		restrictions.add( cb.isTrue( entity.<Boolean>get( "auditResult" ) ) );
		restrictions.add( cb.isFalse( entity.<Boolean>get( "over" ) ) );
		restrictions.add( cb.equal( entity.get( "tradeStatus" ), TradeStatus.Opened ) );
		restrictions.add( cb.lessThan( entity.<Date>get( "endingApplyTime" ), new Date() ) );
		restrictions.add( cb.greaterThan( entity.<Date>get( "chooseTime" ), new Date() ) );
		restrictions.add( cb.or( cb.equal( entity.get( "wayOfChoose" ), ChooseType.Random ),
				cb.equal( entity.get( "wayOfChoose" ), ChooseType.Best ) , cb.equal( entity.get( "wayOfChoose" ), ChooseType.Price ), cb.equal( entity.get( "wayOfChoose" ), ChooseType.Average)) );

		// 过滤已经取消的公告
		restrictions.add( cb.isFalse( entity.<Boolean>get( "cancelled" ) ) );
		String projectName = (String) getParameterValues().get( "projectName" );
		if ( !StringUtils.isBlank( projectName ) )
			restrictions.add( cb.like( entity.get( "projectName" ), getStringRestriction( projectName ) ) );

		String serialNumber = (String) getParameterValues().get( "serialNumber" );
		if ( !StringUtils.isBlank( serialNumber ) )
			restrictions.add( cb.like( entity.get( "serialNumber" ), getStringRestriction( serialNumber ) ) );
		return restrictions;
	}

}
